<script setup>
	import {
		ref,
		computed,
		reactive,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onShow,
		onHide,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		Audio
	} from '/utils/audio.js';
	import {
		getDanCiApi,
		pinxieSubmitApi,
		tijiaoPinXieApi
	} from '../../api/request.js';
	// 1美 2英
	const type = ref(2);
	const audio = ref(null);
	audio.value = new Audio();
	onUnload(() => {
		uni.$emit('pause');
		uni.$emit('playend');
		audio.value.dele();
		audio.value = null;
	});
	onHide(() => {
		uni.$emit('pause');
		uni.$emit('playend');
		audio.value.dele();
		audio.value = null;
	});
	const props = defineProps({});
	let platform = uni.getStorageSync('platform');
	const bofangzhong = ref(false);
	onMounted(() => {
		if (uni.getStorageSync('bofangmoshi')) {
			type.value = uni.getStorageSync('bofangmoshi');
		}
		uni.$on('playend', () => {
			bofangzhong.value = false;
		});
	});
	const indexs = ref(0);
	const list = ref([]);
	const query = ref({
		learning_id: ''
	});
	onLoad(async (e) => {
		query.value.learning_id = e.id;
		let res = await getDanCiApi({
			word_ids: e.word_ids
		});
		list.value = res.data;
		console.log(list.value);
		query.value.indexs = e.indexs;
		play();
	});
	const goback = () => {
		uni.navigateBack();
	};
	const current = ref(0);
	const changeSwiperCurrent = (e) => {
		if (playTimer.value) {
			clearTimeout(playTimer.value);
		}
		selectList.value = [];
		showCuowu.value = 3;
		pinduList.value = [];
		showTishi.value = false;
		value.value = '';
		if (typeof e === 'number' && !isNaN(e)) {
			current.value = e;
		} else {
			current.value = e.detail.current;
		}
		if (current.value == 1) {

			let start =
				type.value == 1 ?
				list.value[indexs.value].detail.mySpeech_us_aria_split[1].s :
				list.value[indexs.value].detail.mySpeech_en_ryan_split[1].s;
			let end = type.value == 1 ?
				list.value[indexs.value].detail.mySpeech_us_aria_split[1].d :
				list.value[indexs.value].detail.mySpeech_en_ryan_split[1].d;
			console.log(start, end);
			bofangzhong.value = false;
			let url =
				type.value == 1 ?
				'https://static.jtsee.com/app_media/words_mp3_v2/us/aria_split/' :
				'https://static.jtsee.com/app_media/words_mp3_v2/gb/ryan_split/';
			setTimeout(() => {
				uni.$emit(
					'playAudio',
					url + list.value[indexs.value].detail.audio_file_name.split,
					true,
					start,
					start + end
				);
			}, 600);
		}
	};
	const sonSwiper = ref(0);
	const changeSonSwiper = (e) => {
		sonSwiper.value = e.detail.current;
	};
	const play = (url = list.value[indexs.value].detail.audio_file_name.word, start, end) => {
		let http =
			type.value == 1 ?
			'https://static.jtsee.com/app_media/words_mp3_v2/us/aria_word/' :
			'https://static.jtsee.com/app_media/words_mp3_v2/gb/ryan_word/';
		bofangzhong.value = true;
		uni.$emit('playAudio', http + `${url}`, true, start, end);
	};
	const returnText = (arr) => {
		let str = '';
		arr.forEach((item) => {
			str += list.value[indexs.value].detail.word[item];
		});
		return str;
	};
	const selectBiao = ref('');
	const center = ref(null);
	const demoVideo = ref(null);
	const showVideo = (e) => {
		center.value = true;
		demoVideo.value = uni.createVideoContext('demoVideo');
		status.value = 2;
	};
	/**
	 * statis 1播放
	 * status 2是透明
	 * status 3是暂停
	 */
	const status = ref(2);
	const timer = ref(null);
	// dianji函数根据stauts的值进行不同的操作
	const dianji = () => {
		if (status.value == 2) {
			status.value = 3;
			timer.value = setTimeout(() => {
				status.value = 2;
				clearTimeout(timer.value);
				timer.value = null;
			}, 1500);
		}
	};
	const plays = () => {
		if (timer.value) {
			clearTimeout(timer.value);
			timer.value = null;
		}
		demoVideo.value.play();
		status.value = 3;
		timer.value = setTimeout(() => {
			status.value = 2;
			clearTimeout(timer.value);
			timer.value = null;
		}, 1500);
	};
	const playTuo = () => {
		try {
			if (timer.value) {
				clearTimeout(timer.value);
				timer.value = null;
			}
			status.value = 1;
			demoVideo.value.pause();
		} catch (e) {
			console.log(e);
		}
	};

	// 拼读
	const showCuowu = ref(3);
	const pinduList = ref([]);
	const shuffledSplit = computed(() => {
		if (list.value[indexs.value].detail.s_split) {
			return list.value[indexs.value].detail.s_split.slice().sort(() => Math.random() - 0.5);
		} else {
			return [];
		}
	});
	const value = ref('');
	const jieguoList = ref({
		correct_word_id: [],
		error_word_id: []
	});
	const duima = async (e) => {
		let id = list.value[indexs.value].id;
		if (iptValue.value !== list.value[indexs.value].detail.word) {
			showCuowu.value = 1;
			showTishi.value = true;
			jieguoList.value.error_word_id.push(id);
			return;
		}
		if (!jieguoList.value.error_word_id.includes(id)) {
			jieguoList.value.correct_word_id.push(id);
		}
		showTishi.value = false;
		showCuowu.value = 2;
		// 播放音频
		if (current.value == 0) {
			setTimeout(() => {
				current.value = 1;
			}, 1200);
		}
		if (indexs.value != list.value.length - 1) {
			indexs.value++;
			iptValue.value = '';
			uni.hideKeyboard();
			current.value = 0;
			play();
		} else {
			uni.showLoading({
				title: '拼写训练完成',
				icon: 'none'
			});
			let res;
			if (query.value.indexs == 2) {
				res = await pinxieSubmitApi({
					learning_id: query.value.learning_id,
					correct_word_id: jieguoList.value.correct_word_id.join(','),
					error_word_id: jieguoList.value.error_word_id.join(',')
				});
			} else {
				res = await tijiaoPinXieApi({
					record3_id: query.value.id
				});
			}
			uni.hideLoading();
			uni.showToast({
				title: res.msg,
				icon: 'none',
				duration: 1200
			});
			setTimeout(() => {
				if (res.code == 1) {
					uni.navigateBack();
					return;
				}
			}, 1200);
			console.log(res);
		}
	};
	const showTishi = ref(true);
	const iptValue = ref('');
	const jiaodian = ref(false);
	const onfoucs = (e) => {
		jiaodian.value = true;
		showTishi.value = false;
	};
	const onBlur = (e) => {
		jiaodian.value = false;
	};
	const playTimer = ref(null);
	//选中的单词
	const selectList = ref([]);
	const addSelectList = (item) => {
		if (selectList.value.length != list.value[indexs.value].detail.s_split.length) {
			selectList.value.push(item);
		}
		if (
			current.value == 1 &&
			selectList.value.length != list.value[indexs.value].detail.s_split.length
		) {
			let start =
				type.value == 1 ?
				list.value[indexs.value].detail.mySpeech_us_aria_split[selectList.value.length + 1].s :
				list.value[indexs.value].detail.mySpeech_en_ryan_split[selectList.value.length + 1].s;

			let end = type.value == 1 ?
				list.value[indexs.value].detail.mySpeech_us_aria_split[selectList.value.length + 1].d :
				list.value[indexs.value].detail.mySpeech_en_ryan_split[selectList.value.length + 1].d;
			console.log(start, end);
			let url =
				type.value == 1 ?
				'https://static.jtsee.com/app_media/words_mp3_v2/us/aria_split/' :
				'https://static.jtsee.com/app_media/words_mp3_v2/gb/ryan_split/';
			setTimeout(() => {
				uni.$emit(
					'playAudio',
					url + list.value[indexs.value].detail.audio_file_name.split,
					true,
					start,
					start + end
				);
			}, 600);
		}

		if (selectList.value.length == list.value[indexs.value].detail.s_split.length) {
			selectList.value.forEach((item, index) => {
				if (
					selectList.value[index] !=
					Object.keys(list.value[indexs.value].detail.s_split[index])[0]
				) {} else if (current.value != 1) {
					if (playTimer.value) {
						clearTimeout(playTimer.value);
						playTimer.value = null;
					}
					playTimer.value = setTimeout(() => {
						play();
						clearTimeout(playTimer.value);
						playTimer.value = null;
					}, 1200);
				} else if (showCuowu.value == 2) {
					current.value = 2;
				}
			});
		}
	};
	const returnStyle = (index) => {
		let str = Object.keys(list.value[indexs.value].detail.s_split[index])[0];
		if (selectList.value.length) {
			if (selectList.value[index] && selectList.value[index] != str) {
				return 'budui';
			} else if (selectList.value[index] == str && index % 2 != 1) {
				return 'active';
			} else if (selectList.value[index] == str && index % 2 == 1) {
				return 'default';
			}
		} else {
			return '';
		}
	};
</script>

<template>
	<view class="wrap" :style="{
            height: platform.gaodu + 'rpx'
        }">
		<view class="header-wrap uni-row" :style="{
                paddingTop: platform.dingbu + 'rpx',
                height: platform.dingbu + 96 + 'rpx'
            }">
			<image class="left" src="/static/img/goback-black.png" @click="goback" mode="widthFix" />
			<view class="title"> 拼写训练（{{ indexs + 1 }}/{{ list.length }}） </view>
			<image class="left" src="/static/img/goback-black.png" mode="widthFix" style="opacity: 0" />
		</view>
		<view class="select-wrap">
			<view class="top-slider uni-row">
				<image @click="changeSwiperCurrent(0)" :src="`/static/img/wolrd/icon${0 == current ? 1 : 2}.png`"
					mode="widthFix" class="icon">
				</image>
				<view class="xian" />
				<image @click="changeSwiperCurrent(1)" :src="`/static/img/wolrd/icon${1 == current ? 1 : 2}.png`"
					mode="widthFix" class="icon">
				</image>
				<view class="xian" />
				<image @click="changeSwiperCurrent(2)" :src="`/static/img/wolrd/icon${2 == current ? 1 : 2}.png`"
					mode="widthFix" class="icon">
				</image>
			</view>
			<view class="top-slider di uni-row">
				<view class="zi" v-for="(item, index) in ['拆分拼写', '自然拼读', '字母拼写']" :key="index"
					@click="changeSwiperCurrent(index)" :class="index == current ? 'active' : 'default'">
					{{ item }}
				</view>
			</view>
		</view>
		<swiper :current="current" :indicator-dots="false" @change="changeSwiperCurrent" :autoplay="false"
			v-if="list && list.length" class="swiper" :style="{
                height: platform.gaodu - platform.dingbu - 96 - 140 - 56 + 'rpx'
            }">
			<swiper-item class="swiper-items" :style="{
                    height: platform.gaodu - platform.dingbu - 96 - 140 - 56 + 'rpx'
                }">
				<!-- 单词 -->
				<view class="dancide uni-row">
					<view class="chaifen-input uni-row" v-for="(item, index) in list[indexs]?.detail?.s_split"
						:key="index" :class="returnStyle(index)">
						<view class="uni-row text">
							{{ Object.keys(item)[0] }}
						</view>
						<text :style="{
                                opacity:
                                    selectList.length === list[indexs].detail.s_split.length ? 1 : 0
                            }">*</text>
					</view>
				</view>
				<!-- 英标 -->
				<view class="yinbiao yinbiaos" @click="play()">
					/
					{{ type == 2 ? list[indexs].detail?.uk : list[indexs].detail?.us }}
					/
				</view>
				<!-- 解释 -->
				<view class="label" style="padding: 0 40rpx">
					<view class="itemss" v-for="(item, index) in list[indexs].detail?.youdao_api?.explains"
						:key="index">
						{{ item }}
					</view>
				</view>
				<view class="textss uni-row">
					<image src="/static/img/wolrd/tishihei.png" class="tishis" @click="play()"></image>
					<image src="/static/img/shuaxin.png" class="laba" @click="selectList = []">
					</image>
				</view>
				<view class="uni-row dibu">
					<view class="dancidess uni-row" hover-class="yanse"
						v-for="(item, index) in list[indexs].detail.s_split" :key="index"
						@click="addSelectList(Object.keys(item)[0])"
						:class="Object.keys(item)[0] == selectList[index] ? 'yanse' : ''">
						{{ Object.keys(item)[0] }}
					</view>
				</view>
			</swiper-item>
			<swiper-item class="swiper-items" :style="{
                    height: platform.gaodu - platform.dingbu - 96 - 140 - 56 + 'rpx'
                }">
				<!-- 单词 -->
				<view class="dancide uni-row">
					<view class="chaifen-input uni-row wordl" v-for="(item, index) in list[indexs].detail.s_split"
						:key="index" :class="returnStyle(index)" :style="
                            selectList.length != list[indexs].detail.s_split.length &&
                            !selectList[index]
                                ? {
                                      padding: '18rpx 6rpx',
                                      background: '#EAEAEA',
                                      borderRadius: '8rpx',
                                      border: '1rpx solid #B3B3B3',
                                      marginRight: '10rpx'
                                  }
                                : { padding: '18rpx 0rpx' }
                        ">
						<view class="uni-row text">
							{{ selectList[index] || Object.keys(item)[0] }}
						</view>
					</view>
				</view>
				<!-- 解释 -->
				<view class="label" style="padding: 0 40rpx">
					<view class="itemss" v-for="(item, index) in list[indexs].detail?.youdao_api?.explains"
						:key="index">
						{{ item }}
					</view>
				</view>
				<view class="textss uni-row">
					<image src="/static/img/wolrd/tishihei.png" class="tishis" @click="play()"></image>
					<image src="/static/img/wolrd/shanchu.png" class="laba" @click="selectList.pop()">
					</image>
				</view>
				<view class="footer uni-row">
					<view class="dancidess uni-row" v-for="(item, index) in shuffledSplit" :key="index"
						:class="index % 2 == 1 ? 'active' : 'default'" @click="addSelectList(Object.keys(item)[0])"
						hover-class="yanse" hover-stay-time="300">
						{{ Object.keys(item)[0] }}
					</view>
				</view>
			</swiper-item>
			<swiper-item class="swiper-items">
				<view class="uni-row top">
					<view class="prompt" v-show="showTishi">
						<view class="content">
							{{ list[indexs].name }}
						</view>
						<view class="yinbiao">
							/
							{{ type == 2 ? list[indexs].detail?.uk : list[indexs].detail?.us }}
							/
						</view>
					</view>
					<input :class="showCuowu == 2 ? 'right' : showCuowu == 1 ? 'active' : 'default'" @focus="onfoucs"
						type="text" v-model="iptValue" class="ipts" @blur="onBlur" />
					<image @touchend.prevent="play()" src="/static/img/laba.png" class="bofangde"></image>
				</view>
				<view class="yinbiao yinbiaos" style="opacity: 0">
					/
					{{ type == 2 ? list[indexs].detail?.uk : list[indexs].detail?.us }}
					/
				</view>
				<view class="label">
					<view class="itemss" v-for="(item, index) in list[indexs]?.youdao_api?.explains" :key="index">
						{{ item }}
					</view>
				</view>
				<view class="textss uni-row">
					<image @touchend.prevent="showTishi = !showTishi" @click.stop="showTishi = !showTishi" :src="
                            !showTishi
                                ? '/static/img/wolrd/tishihei.png'
                                : '/static/img/wolrd/liangtishi.png'
                        " class="tishis"></image>
					<image @touchend.prevent="duima" src="/static/img/wolrd/duila.png" class="laba">
					</image>
				</view>
			</swiper-item>
		</swiper>
	</view>
</template>

<style scoped lang="less">
	.wrap {
		background: url('/static/img/wolrd/xue.png');
		background-size: 100% 100%;

		.header-wrap {
			justify-content: space-between;
			padding-left: 24rpx;
			padding-right: 28rpx;

			.left {
				width: 48rpx;
			}

			.title {
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;
			}
		}

		.select-wrap {
			margin: 0 28rpx;
			background: url('/static/img/wolrd/liucheng.png');
			background-size: 100% 100%;
			height: 140rpx;

			.top-slider {
				padding: 28rpx 0 0;
				justify-content: center;

				.zi {
					font-size: 28rpx;
					transition: 0.3s all;

					&.active {
						color: #ffffff;
					}

					&.default {
						color: #dfddfb;
					}
				}

				.icon {
					width: 40rpx;
				}

				.xian {
					width: 96rpx;
					height: 2rpx;
					background-color: #fff;
					margin: 0 20rpx;
				}
			}

			.di {
				width: 468rpx;
				margin: 0 auto;
				justify-content: space-between;
				padding-top: 8rpx;

				.zi {
					&:nth-child(2) {}

					&.active {
						color: #fff;
					}
				}
			}
		}

		.yanse {
			background-color: rgba(0, 0, 0, 0.4) !important;
		}

		.swiper {
			margin-top: 28rpx;

			.swiper-items {
				position: relative;
				background: #ffffff;
				border-radius: 32rpx;
				padding-top: 148rpx;

				.top {
					position: relative;
					justify-content: center;

					.prompt {
						position: absolute;
						left: 50%;
						top: -118rpx;
						transform: translate(-50%, 0);
						padding: 0 64rpx;
						height: 128.17rpx;
						background: url('/static/img/tishide.png');
						background-size: 100% 100%;

						.content {
							font-size: 36rpx;
							color: #333333;
							margin-top: 8rpx;
							line-height: 50rpx;
						}

						.yinbiao {
							font-size: 24rpx;
							line-height: 34rpx;
							margin-top: 4rpx;
							color: #999999;
						}
					}

					.ipts {
						padding: 0 10rpx;
						font-size: 60rpx;
						color: #333;
						width: 400rpx;
						overflow: hidden;
						text-align: center;
						border-bottom: 6rpx solid #333333;

						&.right {
							border-color: #67c23a;
						}

						&.active {
							border-color: red;
						}
					}

					.bofangde {
						flex-shrink: 0;
						margin-top: 76rpx;
						width: 40rpx;
						margin-left: 10rpx;
						height: 40rpx;
					}
				}

				.dancide {
					justify-content: center;

					.chaifen-input {
						&.budui {
							.text {
								color: #ef4828;
								border-color: transparent;
							}

							text {
								color: #999;
							}
						}

						&.active {
							.text {
								border-color: transparent;
								color: #222868;
							}

							text {
								color: #999;
							}
						}

						&.default {
							.text {
								border-bottom: transparent;
								color: #fa862c;
							}

							text {
								color: #999;
							}
						}

						.text {
							padding: 0 10rpx;
							font-size: 60rpx;
							color: transparent;
							border-bottom: 6rpx solid #333333;
						}

						text {
							color: transparent;
						}

						&:last-child {
							margin-right: 0rpx;

							text {
								display: none;
							}
						}
					}

					.wordl {
						.text {
							padding-left: 0;
							padding-right: 0;
						}

						&:last-child {
							margin-right: 0rpx;
						}
					}
				}

				.textss {
					margin-top: 70rpx;
					padding-right: 48rpx;
					padding-left: 48rpx;
					justify-content: space-between;

					.tishis {
						width: 48rpx;
						height: 48rpx;
					}

					.yinbiao {
						font-weight: 400;
						font-size: 24rpx;
						color: #999999;
					}

					.laba {
						width: 48rpx;
						height: 48rpx;
					}
				}

				.dibu {
					margin-top: 70rpx;
					margin-bottom: 50rpx;
					justify-content: center;
				}

				.footer {
					justify-content: center;
					margin-top: 70rpx;
				}

				.gaibainla {
					justify-content: center;
				}

				.morebde {
					justify-content: center;
				}

				.labasss {
					position: absolute;
					top: 128rpx;
					right: 60rpx;
					z-index: 33;
					width: 42rpx;
					height: 42rpx;
				}

				.yinbiaos {
					font-size: 24rpx;
					color: #999999;
					margin-top: 34rpx;
					text-align: center;
				}

				.label {
					margin: 24rpx 0 24rpx;

					.itemss {
						margin-top: 10rpx;
						text-align: center;
						font-size: 24rpx;
						color: #999999;
					}
				}
			}

			.dancidess {
				font-weight: 500;
				font-size: 54rpx;
				color: #9561f3;
				justify-content: center;
				padding: 0 20rpx;
				height: 80rpx;
				background: #f8f3ff;
				box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(0, 0, 0, 0.27);
				border-radius: 16rpx;
				margin-right: 20rpx;

				&.active {
					color: #222868;
				}

				&.default {
					color: #fa862c;
				}

				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
</style>